#include <pthread.h>
#include <queue>
#include <iostream>
#include <unistd.h>
using namespace std;

queue<int> shared_queue;

pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* producer(void* arg) {
    for (int i = 1; i <= 10; ++i)
    {
        sleep(1);
        pthread_mutex_lock(&mtx);
        shared_queue.push(i);
        cout << "Produced: " << i << endl;

        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mtx);
    }
    return NULL;
}

void* consumer(void* arg) {
    while (true) {
        pthread_mutex_lock(&mtx);

        // 避免虚假唤醒：必须用 while 检查条件
        while (shared_queue.empty()) {
            pthread_cond_wait(&cond, &mtx);
        }

        int val = shared_queue.front();
        shared_queue.pop();
        cout << "Consumed: " << val << endl;

        pthread_mutex_unlock(&mtx);
        usleep(500000); // 模拟消费耗时
    }
    return NULL;
}

int main() {
    pthread_t prod, cons;
    pthread_create(&prod, NULL, producer, NULL);
    pthread_create(&cons, NULL, consumer, NULL);

    pthread_join(prod, NULL);
    // 注意：consumer 是无限循环，如需退出要增加退出条件

    // 不会走到这，但你可以选择在线程内处理退出逻辑
    return 0;
}
